/**
 * AI聊天功能
 */
 class AIChatManager {
      constructor() {
          this.isOpen = false;
          this.isLoading = false;
          this.userInfo = null;
          this.selectedModelId = null; // 添加选中的模型ID
          this.init();
      }

      init() {
          this.bindEvents();
          this.loadUserInfo();
          this.loadUsageInfo();
          this.loadAvailableModels(); // 加载可用模型
      }

       bindEvents() {
      // 绑定FAB按钮点击事件
      const fabBtn = document.getElementById('ai-chat-fab');
      if (fabBtn) {
          fabBtn.addEventListener('click', () => this.toggleChat());
      }

      // 绑定关闭按钮事件
      const closeBtn = document.querySelector('.ai-chat-close');
      if (closeBtn) {
          closeBtn.addEventListener('click', () => this.closeChat());
      }

      // 绑定模态框背景点击事件
      const modal = document.getElementById('ai-chat-modal');
      if (modal) {
          modal.addEventListener('click', (e) => {
              if (e.target === modal) {
                  this.closeChat();
              }
          });
      }

      // 绑定发送按钮事件
      const sendBtn = document.getElementById('ai-chat-send');
      if (sendBtn) {
          sendBtn.addEventListener('click', () => this.sendMessage());
      }

      // 绑定输入框回车事件
      const input = document.getElementById('ai-chat-input');
      if (input) {
          input.addEventListener('keydown', (e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  this.sendMessage();
              }
          });
      }

      // 绑定模型选择变更事件
      const modelSelect = document.getElementById('ai-model-select');
      if (modelSelect) {
          modelSelect.addEventListener('change', (e) => {
              this.selectedModelId = e.target.value;
              this.updateModelInfo();
          });
      }
  }

  toggleChat() {
      if (this.isOpen) {
          this.closeChat();
      } else {
          this.openChat();
      }
  }

  closeChat() {
      const modal = document.getElementById('ai-chat-modal');
      if (modal) {
          modal.style.display = 'none';
          this.isOpen = false;
      }
  }

  async loadUserInfo() {
      try {
          const response = await fetch('/xuanzheng-company/getCurrentUser');
          if (response.ok) {
              this.userInfo = await response.json();
          }
      } catch (error) {
          // console.error('加载用户信息失败:', error);
      }
  }

  async loadUsageInfo() {
      try {
          const response = await fetch('/xuanzheng-company/aiUsageInfo');
          if (response.ok) {
              const data = await response.json();
              this.updateUsageDisplay(data);
          }
      } catch (error) {
          // console.error('加载使用信息失败:', error);
          this.updateUsageDisplay({ remainingQuestions: '未知', currentModel: '未知' });
      }
  }

  updateUsageDisplay(data) {
      const usageInfo = document.getElementById('ai-usage-info');

      if (usageInfo) {
          usageInfo.textContent = `今日剩余提问次数: ${data.remainingQuestions || '未知'}`;
      }
  }

  addAIMessage(message) {
      const messagesContainer = document.getElementById('ai-chat-messages');
      if (!messagesContainer) return;

      const messageDiv = document.createElement('div');
      messageDiv.className = 'ai-message';
      messageDiv.innerHTML = `
          <div class="message-content">
              <i class="fas fa-robot"></i>
              <span>${this.escapeHtml(message)}</span>
          </div>
      `;

      messagesContainer.appendChild(messageDiv);
      this.scrollToBottom();
  }

  addLoadingMessage() {
      const messagesContainer = document.getElementById('ai-chat-messages');
      if (!messagesContainer) return null;

      const messageId = 'loading-' + Date.now();
      const messageDiv = document.createElement('div');
      messageDiv.className = 'ai-message';
      messageDiv.id = messageId;
      messageDiv.innerHTML = `
          <div class="message-content">
              <i class="fas fa-robot"></i>
              <span class="ai-loading">AI正在思考中</span>
          </div>
      `;

      messagesContainer.appendChild(messageDiv);
      this.scrollToBottom();
      return messageId;
  }

  removeMessage(messageId) {
      const message = document.getElementById(messageId);
      if (message) {
          message.remove();
      }
  }

  openChat() {
      const modal = document.getElementById('ai-chat-modal');
      if (modal) {
          modal.style.display = 'block';
          this.isOpen = true;
          // 刷新使用信息
          this.loadUsageInfo();
      }
  }

  async loadAvailableModels() {
      try {
          const response = await fetch('/xuanzheng-company/aiModels');
          if (response.ok) {
              const data = await response.json();
              this.updateChatModelSelect(data);
          }
      } catch (error) {
          // console.error('加载可用模型失败:', error);
      }
  }

  updateChatModelSelect(models) {
      const select = document.getElementById('ai-model-select');
      if (!select) return;

      // 清空现有选项
      select.innerHTML = '';
      
      // 添加启用的模型
      const enabledModels = models.filter(model => model.status === 1);
      if (enabledModels.length === 0) {
          select.innerHTML = '<option value="">暂无可用模型</option>';
          return;
      }

      enabledModels.forEach(model => {
          const option = document.createElement('option');
          option.value = model.id;
          option.textContent = model.name;
          select.appendChild(option);
      });

      // 设置默认选择
      if (enabledModels.length > 0 && !this.selectedModelId) {
          this.selectedModelId = enabledModels[0].id;
          select.value = this.selectedModelId;
      }
  }

  updateModelInfo() {
      // 更新模型相关信息显示
      // console.log('选择的模型ID:', this.selectedModelId);
  }

  async sendMessage() {
      const input = document.getElementById('ai-chat-input');
      if (!input || this.isLoading) return;

      const message = input.value.trim();
      if (!message) {
          alert('请输入问题');
          return;
      }

      if (!this.selectedModelId) {
          alert('请选择AI模型');
          return;
      }

      // 添加用户消息
      this.addUserMessage(message);
      input.value = '';

      // 设置加载状态
      this.setLoading(true);
      const loadingId = this.addLoadingMessage();

      try {
          const response = await fetch('/xuanzheng-company/aiChat', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                  message: message,
                  modelId: this.selectedModelId
              })
          });

          const data = await response.json();
          
          // 移除加载消息
          if (loadingId) {
              this.removeMessage(loadingId);
          }

          if (data.success) {
              this.addAIMessage(data.answer || data.response);
              this.loadUsageInfo(); // 更新使用次数
          } else {
              this.addAIMessage('抱歉，处理您的问题时出现了错误：' + (data.message || '未知错误'));
          }
      } catch (error) {
          // console.error('发送消息失败:', error);
          if (loadingId) {
              this.removeMessage(loadingId);
          }
          this.addAIMessage('抱歉，网络连接出现问题，请稍后再试。');
      } finally {
          this.setLoading(false);
      }
  }

  addUserMessage(message) {
      const messagesContainer = document.getElementById('ai-chat-messages');
      if (!messagesContainer) return;

      const messageDiv = document.createElement('div');
      messageDiv.className = 'user-message';
      messageDiv.innerHTML = `
          <div class="message-content">
              <span>${this.escapeHtml(message)}</span>
              <i class="fas fa-user"></i>
          </div>
      `;

      messagesContainer.appendChild(messageDiv);
      this.scrollToBottom();
  }

  setLoading(isLoading) {
      this.isLoading = isLoading;
      const sendBtn = document.getElementById('ai-chat-send');
      const input = document.getElementById('ai-chat-input');

      if (sendBtn) {
          sendBtn.disabled = isLoading;
          if (isLoading) {
              sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发送中';
          } else {
              sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 发送';
          }
      }

      if (input) {
          input.disabled = isLoading;
      }
  }

  scrollToBottom() {
      const messagesContainer = document.getElementById('ai-chat-messages');
      if (messagesContainer) {
          setTimeout(() => {
              messagesContainer.scrollTop = messagesContainer.scrollHeight;
          }, 100);
      }
  }

  escapeHtml(text) {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
  }

  showError(message) {
      alert(message);
  }
}

// AI设置管理类（仅管理员使用）
class AISettingsManager {
    constructor() {
        this.init();
    }

    init() {
        // 检查当前页面是否有AI设置功能
        if (document.getElementById('ai-settings')) {
            this.bindSettingsEvents();
            this.loadSettings();
        }
    }

    bindSettingsEvents() {
        // 绑定模型管理事件
        const addModelBtn = document.getElementById('add-model-btn');
        if (addModelBtn) {
            addModelBtn.addEventListener('click', () => this.showAddModelDialog());
        }

        const refreshModelsBtn = document.getElementById('refresh-models-btn');
        if (refreshModelsBtn) {
            refreshModelsBtn.addEventListener('click', () => this.loadModels());
        }

        // 绑定限制设置事件
        const updateLimitBtn = document.getElementById('update-default-limit-btn');
        if (updateLimitBtn) {
            updateLimitBtn.addEventListener('click', () => this.updateDefaultLimit());
        }

        const searchUserBtn = document.getElementById('search-user-btn');
        if (searchUserBtn) {
            searchUserBtn.addEventListener('click', () => this.searchUser());
        }

        // 绑定系统设置事件
        const updateEnabledBtn = document.getElementById('update-ai-enabled-btn');
        if (updateEnabledBtn) {
            updateEnabledBtn.addEventListener('click', () => this.updateAIEnabled());
        }

        const updateModelBtn = document.getElementById('update-default-model-btn');
        if (updateModelBtn) {
            updateModelBtn.addEventListener('click', () => this.updateDefaultModel());
        }
    }

    async loadSettings() {
        await Promise.all([
            this.loadModels(),
            this.loadSystemSettings()
        ]);
    }

    async loadModels() {
        try {
            const response = await fetch('/xuanzheng-company/aiModels');
            if (response.ok) {
                const data = await response.json();
                this.renderModels(data);
                this.updateModelSelect(data);
            }
        } catch (error) {
            // console.error('加载模型列表失败:', error);
        }
    }

    renderModels(models) {
        const container = document.getElementById('ai-models-list');
        if (!container) return;

        if (!models || models.length === 0) {
            container.innerHTML = '<p class="text-muted">暂无AI模型</p>';
            return;
        }

        container.innerHTML = models.map(model => `
            <div class="model-item">
                <div class="model-info">
                    <h4>${model.name}</h4>
                    <p>${model.description || '暂无描述'}</p>
                    <small>API地址: ${model.apiUrl}</small>
                </div>
                <div class="model-actions">
                    <span class="model-status ${model.status === 1 ? 'active' : 'inactive'}">
                        ${model.status === 1 ? '启用' : '禁用'}
                    </span>
                    <button class="btn btn-sm btn-primary" onclick="aiSettings.editModel('${model.id}')">编辑</button>
                    <button class="btn btn-sm ${model.status === 1 ? 'btn-warning' : 'btn-success'}" 
                            onclick="aiSettings.toggleModel('${model.id}', ${model.status})">
                        ${model.status === 1 ? '禁用' : '启用'}
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="aiSettings.deleteModel('${model.id}')">删除</button>
                </div>
            </div>
        `).join('');
    }

    updateModelSelect(models) {
        const select = document.getElementById('default-model-select');
        if (!select) return;

        select.innerHTML = models
            .filter(model => model.status === 1)
            .map(model => `<option value="${model.id}">${model.name}</option>`)
            .join('');
    }

    async loadSystemSettings() {
        try {
            const response = await fetch('/xuanzheng-company/aiSystemSettings');
            if (response.ok) {
                const data = await response.json();
                this.updateSettingsUI(data);
            }
        } catch (error) {
            // console.error('加载系统设置失败:', error);
        }
    }

    updateSettingsUI(settings) {
        // 更新默认限制
        const limitInput = document.getElementById('default-daily-limit');
        if (limitInput && settings.defaultDailyLimit) {
            limitInput.value = settings.defaultDailyLimit;
        }

        // 更新AI启用状态
        const enabledSelect = document.getElementById('ai-enabled');
        if (enabledSelect && settings.aiEnabled !== undefined) {
            enabledSelect.value = settings.aiEnabled;
        }

        // 更新默认模型
        const modelSelect = document.getElementById('default-model-select');
        if (modelSelect && settings.defaultModelId) {
            modelSelect.value = settings.defaultModelId;
        }
    }

    // 其他设置管理方法...
    async updateDefaultLimit() {
        const input = document.getElementById('default-daily-limit');
        const value = input ? input.value : '';

        if (!value || isNaN(value) || value < 1) {
            alert('请输入有效的限制数量');
            return;
        }

        try {
            const response = await fetch('/xuanzheng-company/updateAISetting', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    key: 'default_daily_limit',
                    value: value
                })
            });

            const data = await response.json();
            if (data.success) {
                alert('更新成功');
            } else {
                alert('更新失败: ' + data.message);
            }
        } catch (error) {
            // console.error('更新失败:', error);
            alert('更新失败');
        }
    }

    // 更多方法实现...
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化AI聊天
    window.aiChatManager = new AIChatManager();
    
    // 如果是管理员页面，初始化AI设置
    if (document.getElementById('ai-settings')) {
        window.aiSettings = new AISettingsManager();
    }
});